<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\trait\SettingsTrait;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageTravel;
use plugin\ycMassage\utils\enum\State;
use support\Request;
use think\facade\Db;

class TravelController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->addScreen('name', 'input', '出行', [
            'placeholder' => '出行搜索'
        ]);
        $builder->addScreen('state', 'select', '状态', [
            'options' => State::getOptions()
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addTopButton('add', '添加出行', [
            'api'       => $this->pluginPrefix . '/admin/Travel/create',
            'path' => '/Travel/create',
            'type'      => 'modal'
        ], [
            'title' => '添加出行',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('update', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Travel/update',
            'path' => '/Travel/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('del', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/Travel/delete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('title', '出行', [])
            ->addColumn('start_distance', '起步距离(千米)', [
                'width' => 160
            ])
            ->addColumn('start_price', '起步价(元)', [
                'width' => 100
            ])
            ->addColumn('mileage_price', '里程价(元)', [
                'width' => 100
            ])
            ->addColumn('virtually_mileage', '虚拟里程(%)', [
                'width' => 100
            ])
            ->addColumn('province', '省', [
                'width' => 100
            ])
            ->addColumn('city', '市', [
                'width' => 100
            ])
            ->addColumn('start_time', '开始时间', [
                'width' => 120
            ])
            ->addColumn('end_time', '结束时间', [
                'width' => 120
            ])
            ->addColumn('commuting', '每公里通勤时间(分钟)', [
                'width' => 160
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Travel/updateState',
                    'checked' => State::YES,
                    'unchecked' => State::NO
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['t.saas_appid', '=', $request->saas_appid]
        ];
        $name = $request->get('name');
        if ($name) {
            $where[] = ['t.title', 'like', "%{$name}%"];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['t.state', '=', $state];
        }
        $data = MassageTravel::where($where)
            ->alias('t')
            ->order('t.create_time desc')
            ->field('t.*')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $MassageTravel = new MassageTravel;
                $D['saas_appid'] = $saas_appid;
                list($province_id, $city_id) = $D['regions'];
                $MassageTravel->province_id = (int)$province_id;
                $MassageTravel->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageTravel->city_id = $city_id;
                $MassageTravel->city = MassageRegions::where(['id' => $city_id])->value('title');
                if (!empty($D['time'])) {
                    list($start_time, $end_time) = $D['time'];
                    $MassageTravel->start_time = $start_time;
                    $MassageTravel->end_time = $end_time;
                }
                $MassageTravel->save($D);
                Db::commit();
                return $this->success('添加成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '出行名称', '', [
            'col'           => 12
        ]);
        $builder->addRow('start_distance', 'number', '起步距离(千米)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $builder->addRow('start_price', 'number', '起步价格(元)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 2,
                'controls' => false
            ]
        ]);
        $builder->addRow('mileage_price', 'number', '里程价格(元/千米)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 2,
                'controls' => false
            ]
        ]);
        $builder->addRow('virtually_mileage', 'number', '虚拟里程(%)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $regionsData = [];
        foreach ($regions as $key => $province) {
            $temp = [
                'id' => $province['id'],
                'title' => $province['title'],
                'children' => []
            ];
            foreach ($province['children'] as $key => $city) {
                $temp['children'][] = [
                    'id' => $city['id'],
                    'title' => $city['title'],
                    'children' => []
                ];
            }
            $regionsData[] = $temp;
        }
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regionsData,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('time', 'time', '可用时间', '', [
            'col'           => 12,
            'props' => [
                'is-range' => true,
                'arrow-control' => true,
                'start-placeholder' => "起始时间",
                'end-placeholder' => "结束时间"
            ]
        ]);
        $builder->addRow('commuting', 'number', '每公里通勤时间(分钟)', '', [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 24,
            'options' => State::getOptions()
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $saas_appid = $request->saas_appid;
        $id = $request->get('id');
        $MassageTravel = MassageTravel::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageTravel) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                list($province_id, $city_id) = $D['regions'];
                $MassageTravel->province_id = (int)$province_id;
                $MassageTravel->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageTravel->city_id = $city_id;
                $MassageTravel->city = MassageRegions::where(['id' => $city_id])->value('title');
                if (!empty($D['time'])) {
                    list($start_time, $end_time) = $D['time'];
                    $MassageTravel->start_time = $start_time;
                    $MassageTravel->end_time = $end_time;
                }
                $MassageTravel->save($D);
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        if ($MassageTravel->start_time && $MassageTravel->end_time) {
            $MassageTravel->time = [$MassageTravel->start_time, $MassageTravel->end_time];
        }
        $MassageTravel->regions = [$MassageTravel->province_id, $MassageTravel->city_id];
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '出行名称', '', [
            'col'           => 12
        ]);
        $builder->addRow('start_distance', 'number', '起步距离(千米)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $builder->addRow('start_price', 'number', '起步价格(元)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 2,
                'controls' => false
            ]
        ]);
        $builder->addRow('mileage_price', 'number', '里程价格(元/千米)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 2,
                'controls' => false
            ]
        ]);
        $builder->addRow('virtually_mileage', 'number', '虚拟里程(%)', 0, [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $regionsData = [];
        foreach ($regions as $key => $province) {
            $temp = [
                'id' => $province['id'],
                'title' => $province['title'],
                'children' => []
            ];
            foreach ($province['children'] as $key => $city) {
                $temp['children'][] = [
                    'id' => $city['id'],
                    'title' => $city['title'],
                    'children' => []
                ];
            }
            $regionsData[] = $temp;
        }
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regionsData,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('time', 'time', '可用时间', '', [
            'col'           => 12,
            'props' => [
                'is-range' => true,
                'arrow-control' => true,
                'start-placeholder' => "起始时间",
                'end-placeholder' => "结束时间"
            ]
        ]);
        $builder->addRow('commuting', 'number', '每公里通勤时间(分钟)', '', [
            'col'           => 12,
            'props' => [
                'min' => 0,
                'precision' => 0,
                'controls' => false
            ]
        ]);
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 24,
            'options' => State::getOptions()
        ]);
        $data = $builder->setData($MassageTravel)->create();
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $MassageTravel = MassageTravel::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        $MassageTravel->state = $MassageTravel->state == State::YES['value'] ? State::NO['value'] : State::YES['value'];
        if ($MassageTravel->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageTravel = MassageTravel::where($where)->find();
        if (!$MassageTravel) {
            return $this->fail('数据不存在');
        }
        if ($MassageTravel->delete()) {
            return $this->success('删除成功');
        }
        return $this->fail('删除失败');
    }
}
